import { MapControls, OrbitControls } from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import { vec3 } from "@react-three/rapier";
import { Ref, useEffect, useRef, useState } from "react";
import { MOUSE, Vector2, Vector3 } from "three";
import type { MapControls as MapControlsImpl } from 'three-stdlib'



export default function ChooseThemeCamera(props: {
    target: number[],
}) {
    const cameraRef = useRef<MapControlsImpl>(null)
    const [target, setTarget] = useState([0, 0, 0])
    const [newTarget, setNewTarget] = useState(props.target)

    useEffect(() => {
        if (props.target != target) {
            setNewTarget(props.target)
        }
    }, [props.target])

    useFrame((state, delta) => {
        const newTargetVector = new Vector3(newTarget[0], newTarget[1], newTarget[2])
        const targetVector = new Vector3(target[0], target[1], target[2])
        const smoothedTarget = new Vector3()
        if (cameraRef.current) {
            if (newTarget != target) {
                cameraRef.current.maxAzimuthAngle = cameraRef.current.getAzimuthalAngle()
                cameraRef.current.maxPolarAngle = cameraRef.current.getPolarAngle()
                cameraRef.current.minAzimuthAngle = cameraRef.current.getAzimuthalAngle()
                cameraRef.current.minPolarAngle = cameraRef.current.getPolarAngle()
                cameraRef.current.maxDistance = cameraRef.current.getDistance()
                cameraRef.current.minDistance = cameraRef.current.getDistance()
                smoothedTarget.lerpVectors(cameraRef.current.target, newTargetVector, delta * 5)
                cameraRef.current.target.copy(smoothedTarget)
            }
            if (cameraRef.current.target.distanceTo(newTargetVector) < 0.5) {
                cameraRef.current.minAzimuthAngle = -Infinity
                cameraRef.current.maxAzimuthAngle = +Infinity
                cameraRef.current.minPolarAngle = 0
                cameraRef.current.maxPolarAngle = Math.PI / 3
                cameraRef.current.minDistance = 5
                cameraRef.current.maxDistance = 10
                setTarget(newTarget)
            }
        }
    })

    return (
        <OrbitControls
            //@ts-ignore
            ref={cameraRef}
            maxDistance={10}
            minDistance={5}
            enablePan={false}
            maxPolarAngle={Math.PI / 3}
            minPolarAngle={0}
        />
    )
}